package org.example.ims.Configuration;

import jakarta.servlet.http.HttpServletResponse;
import org.example.ims.Service.User.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import java.io.IOException;


@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        // 配置认证管理器
        http.getSharedObject(AuthenticationManagerBuilder.class)
                .userDetailsService(customUserDetailsService)
                .passwordEncoder(passwordEncoder);

        http
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/login", "/register/**").permitAll() // 公开路径
                        .requestMatchers("/admin/**").hasRole("ADMIN")     // 管理员路径
                        .anyRequest().authenticated()                      // 其他需要认证
                )
                .formLogin(form -> form
                        .loginPage("/login")
                        .loginProcessingUrl("/login")
                        .successHandler((req, resp, auth) -> resp.setStatus(HttpStatus.OK.value()))
                        .failureHandler((request, response, exception) -> {
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            response.setContentType("application/json;charset=UTF-8");
                            try {
                                response.getWriter().write("{\"error\": \"认证失败\"}");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        })
                        .permitAll()
                )
                .logout(logout -> logout
                        .logoutUrl("/logout")
                        .permitAll()
                )
                .csrf(csrf -> csrf.disable()); // 前后端分离项目通常禁用CSRF


        return http.build();
    }

}